var WPV_STYLES;

(function($, undefined) {

    var width = 150;

    $(function() {
        WPV_STYLES.init();
    });

    WPV_STYLES = {
        // create interface
        init: function() {
            var config = WPVSS.config;
            var s = $('<div id="style-switcher"></div>').css('left', -width);

            $(config.groups).each(function(i, group) {
                var section = $('<section></section>').addClass('style-switcher-group clearfix').addClass(group.type);

                if (group.name != '&nbsp;') section.append('<h4>' + group.name + '</h4>');

                var section_contents = $('<div></div>').addClass('section-contents').appendTo(section);

                switch (group.type) {
                    case 'buttons':
                        $(group.options).each(function(bi, opt) {
                            var button = $('<a></a>').attr('href', opt.url);

                            if (opt.name) {
                                button.attr('name', opt.name);
                            }

                            // mark active buttons
                            if (
                                (group.action == 'redirect' && window.location.url == opt.url) || (group.action == 'load_css' && WPV_STYLES.readcookie('style-' + group.name) == opt.url) || (WPV_STYLES.readcookie('style-' + group.name) === null && bi === 0 && group.name != '&nbsp;')) {
                                button.addClass('active');
                            }

                            // is this an image or a text button?
                            if (opt.image) {
                                button.html('<img src="' + WPVSS.uri + 'style_switcher/buttons/' + opt.image + '" />');
                            } else if (opt.name) {
                                button.html(opt.name);
                            }

                            button.click(function() {
                                if (group.name != '&nbsp;') $(this).addClass('active').siblings().removeClass('active');

                                // pass the group name and url to the correct action
                                WPV_STYLES[group.action](group.name, opt.url, opt);

                                return false;
                            });

                            button.appendTo(section_contents);
                        });
                        break;
                    case 'select':
                        var select = $('<select></select>');

                        if (group.prompt) {
                            select.append('<option></option>');
                        }

                        $(group.options).each(function(io, opt) {
                            var new_option = $('<option></option>').attr('value', opt.url).text(opt.name).appendTo(select).data('opt', opt);

                            if ((group.action == 'redirect' && window.location.href == opt.url) || (group.action == 'load_css' && WPV_STYLES.readcookie('style-' + group.name) == opt.url)) {
                                new_option.prop('selected', true);
                            }

                        });

                        select.change(function() {
                            if ($(this).val()) {
                                WPV_STYLES[group.action](group.name, $(this).val(), $(':selected', this).data('opt'));
                            }
                        });

                        var select_wrp = $('<div class="clearfix"></div>');

                        select.appendTo(select_wrp);

                        $('<div class="prev">&lt;</div>').click(function() {
                            if (select[0].selectedIndex > 0) {
                                select[0].selectedIndex--;
                                select.change();
                            } else {
                                select[0].selectedIndex = select.find('option').length - 1;
                                select.change();
                            }
                        }).appendTo(select_wrp);
                        $('<div class="next">&gt;</div>').click(function() {
                            if (select[0].selectedIndex + 1 < select.find('option').length) {
                                select[0].selectedIndex++;
                                select.change();
                            } else {
                                select[0].selectedIndex = 0;
                                select.change();
                            }
                        }).appendTo(select_wrp);

                        select_wrp.appendTo(section_contents);
                        break;
                }

                section.appendTo(s);
            });

            var hasTeaser = !!config.teaser;
            var teaser;

            if (hasTeaser) {
                teaser = $('<div id="ss-teaser">').html(config.teaser).append(
                    $('<div class="close icon" />').click(function() {
                        teaser.fadeOut(200, function() {
                            WPV_STYLES.setcookie('no-teaser', true, 1);
                            setTimeout(function() {
                                teaser.remove();
                            }, 500);
                        });
                    }));
            }

            var toggle_button = $('<span id="toggle-style-switcher"></span>').click(function() {
                WPV_STYLES.setcookie('style-closed', $(this).is('.open'), 1);

                s.toggleClass('open');
                s.animate({
                    left: $(this).is('.open') ? -width : 0,
                    avoidTransforms: true
                }, 400, function() {
                    toggle_button.toggleClass('open');

                    if (hasTeaser) {
                        WPV_STYLES.setcookie('no-teaser', true, 1);
                        setTimeout(function() {
                            teaser.remove();
                        }, 500);
                    }
                });
            });

            if (hasTeaser && WPV_STYLES.readcookie('no-teaser') != 'true')
                s.append(teaser);

            toggle_button.appendTo(s);

            $('body').append(s);

            $(window).trigger('wpv-ss-loaded');
        },

        // load_css action
        load_css: function(group, href) {
            if (href.match(/clear_css/)) {
                href = href.split('|');
                for (var i = 1; i < href.length; i++) {
                    this.setcookie('style-' + href[i], '', -1);
                }
            } else {
                this.setcookie('style-' + group, href, 1);
            }

            window.location.reload();
            return;
        },

        // redirect action
        redirect: function(group, href) {
            window.location.href = href;
        },

        // cookie helpers (see http://www.quirksmode.org/js/cookies.html)
        setcookie: function(name, value, days) {
            name = name.replace(/\s+/, '-').toLowerCase();
            var expires;

            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                expires = "; expires=" + date.toGMTString();
            } else {
                expires = "";
            }
            document.cookie = name + "=" + value + expires + "; path=/";
        },

        readcookie: function(name) {
            name = name.replace(/\s+/, '-').toLowerCase();

            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
            }
            return null;
        }

    };

})(jQuery);
